package com.beiji.lib.pen

import android.text.TextUtils
import android.util.Log

/**
 * Log util
 * Created by X on 2018/6/16.
 */
object PenLog {

    private const val TAG_PREFIX = "PenLog"

    private var isDebug: Boolean = true

    @JvmStatic
    fun init(isDebug: Boolean) {
        PenLog.isDebug = isDebug
    }

    @JvmStatic
    fun v(msg: String) {
        if (isDebug) {
            Log.v(generateTag(), msg)
        }
    }

    @JvmStatic
    fun d(msg: String) {
        if (isDebug) {
            Log.d(generateTag(), msg)
        }
    }

    @JvmStatic
    fun i(msg: String) {
        if (isDebug) {
            Log.i(generateTag(), msg)
        }
    }

    @JvmStatic
    fun w(msg: String) {
        if (isDebug) {
            Log.w(generateTag(), msg)
        }
    }

    @JvmStatic
    fun e(msg: String) {
        if (isDebug) {
            Log.e(generateTag(), msg)
        }
    }

    @JvmStatic
    fun wtf(msg: String) {
        if (isDebug) {
            Log.wtf(generateTag(), msg)
        }
    }

    @JvmStatic
    fun v(tag: String, msg: String) {
        if (isDebug) {
            Log.v(tag, msg)
        }
    }

    @JvmStatic
    fun d(tag: String, msg: String) {
        if (isDebug) {
            Log.d(tag, msg)
        }
    }

    @JvmStatic
    fun i(tag: String, msg: String) {
        if (isDebug) {
            Log.i(tag, msg)
        }
    }

    @JvmStatic
    fun w(tag: String, msg: String) {
        if (isDebug) {
            Log.w(tag, msg)
        }
    }

    @JvmStatic
    fun e(tag: String, msg: String) {
        if (isDebug) {
            Log.e(tag, msg)
        }
    }

    @JvmStatic
    fun wtf(tag: String, msg: String) {
        if (isDebug) {
            Log.wtf(tag, msg)
        }
    }

    private fun generateTag(): String {
        val caller = Thread.currentThread().stackTrace[4]
        var tag = "%s.%s()" // 占位符
        try {
            var callerClazzName = caller.className // 获取到类名
            callerClazzName = callerClazzName.substring(callerClazzName.lastIndexOf(".") + 1)
            tag = String.format(tag, callerClazzName, caller.methodName) // 替换
        } catch (e: IndexOutOfBoundsException) {
            Log.d(TAG_PREFIX, e.toString())
            return TAG_PREFIX
        }

        return if (TextUtils.isEmpty(TAG_PREFIX)) tag else "$TAG_PREFIX,$tag"
    }

}